import './style.css'
import * as THREE from 'three';
import WebGL from 'three/addons/capabilities/WebGL.js';
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"


/* 场景 */
const scene = new THREE.Scene();
/* 透视摄像机 */
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
/* 渲染器 */
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 添加世界坐标辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

// 创建几何体
const geometry = new THREE.BufferGeometry();
const cubegeometry = new THREE.BoxGeometry(1,1,1)
// 创建顶点数据
// const vertices = new Float32Array([
//   -1.0, -1.0, 0.0,
//   1.0, -1.0, 0.0,
//   1.0, 1.0, 0.0,
//   1.0, 1.0, 0.0,
//   -1.0 , 1.0, 0,
//   -1.0, -1.0, 0
// ])
// // 创建顶点属性
// geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3))
// console.log(geometry);
/* ---- */
const vertices = new Float32Array([
  -1.0, -1.0, 0,
  1.0, -1.0, 0,
  1.0, 1.0, 0,
  -1.0, 1.0, 0
])
// 创建顶点属性
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3))
// 创建索引
const indices = new Uint16Array([0, 1, 2, 2, 3, 0])
geometry.setIndex(new THREE.BufferAttribute(indices, 1))
console.log(geometry);

// 设置两个顶点组 设置两个材质
geometry.addGroup(0,3,0)
geometry.addGroup(3,3,1)
// 创建材质
const material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  wireframe: true, //线框
  side: THREE.DoubleSide
})
const material1 = new THREE.MeshBasicMaterial({
  color: 0xff0000,
  side: THREE.DoubleSide
})
const material2 = new THREE.MeshBasicMaterial({
  color: 0xffff00

})
const material3 = new THREE.MeshBasicMaterial({
  color: 0x0000ff
})
const material4 = new THREE.MeshBasicMaterial({
  color: 0xff00ff
})
const material5 = new THREE.MeshBasicMaterial({
  color: 0xff00f0
})
const plane = new THREE.Mesh(geometry, [material,material1])

const sube = new THREE.Mesh(cubegeometry,[material,material1,material2,material3,material4,material5])

sube.position.x = 2

scene.add(sube)

//添加到场景
scene.add(plane);

camera.position.z = 5;
camera.position.y = 2;
camera.position.x = 2;
camera.lookAt(0, 0, 0)

// 添加轨道控制器
const controls = new OrbitControls(camera, renderer.domElement)
// 设置带阻尼的惯性
controls.enableDamping = true;
// 设置阻尼系数 
controls.dampingFactor = 0.01;
// 自动旋转
// controls.autoRotate = true;

function animate() {
  requestAnimationFrame(animate);
  controls.update()
  renderer.render(scene, camera);
}
// webgl兼容性检查
if (WebGL.isWebGLAvailable()) {
  animate();
} else {
  const warning = WebGL.getWebGLErrorMessage();
  document.getElementById('app').appendChild(warning);

}


/* 动态窗口 */
window.addEventListener('resize', function () {
  // 重置浏览器宽高比
  renderer.setSize(this.window.innerWidth, this.window.innerHeight);
  //重置相机宽高比
  camera.aspect = this.window.innerWidth / this.window.innerHeight;
  // 更新相机投影矩阵
  camera.updateProjectionMatrix();
})



